<template>
  <div class="components-prod-transport">
    <el-form-item
      :label="$t('product.shippinngs')"
      :rules="[{ required: true, message: $t('product.shippingtBeEmpty')}]"
    >
      <el-radio
        v-model="tableRate"
        :label="0"
      >
        {{ $t('product.freeShipping') }}
      </el-radio>
      <el-radio
        v-model="tableRate"
        :label="-1"
        @change="freight"
      >
        {{ $t('menuList.fixedFreight') }}
      </el-radio>
      <el-radio
        v-model="tableRate"
        :label="1"
      >
        {{ $t('menuList.freTempl') }}
      </el-radio>
    </el-form-item>

    <!-- 运费模板 -->
    <el-form-item
      v-if="tableRate>0"
      :label-width="$t('language')==='English'?'180px':''"
      :label="$t('menuList.freTempl')"
      prop="deliveryTemplateId"
    >
      <el-select
        v-if="tableRate>0"
        v-model="transportId"
      >
        <el-option
          v-for="transport in transportList"
          :key="transport.transportId"
          :placeholder="$t('tip.select')"
          :label="transport.transName"
          :value="transport.transportId"
        />
      </el-select>
      <!--      新建/刷新-->
      <el-button
        link
        type="primary"
        @click="refreshChange"
      >
        {{ $t('transport.refresh') }}
      </el-button>
      <el-divider direction="vertical" />
      <el-button
        link
        type="primary"
        @click.stop="onAddOrUpdate()"
      >
        {{ $t('transport.newConstruction') }}
      </el-button>
    </el-form-item>

    <!-- 固定运费 -->
    <el-form-item
      v-if="tableRate===-1"
      :label-width="$t('language')==='English'?'180px':''"
      :label="$t('menuList.fixedFreight')"
    >
      <div
        class="freight"
        style="width: 175px;"
      >
        <el-input
          v-model="deliveryAmount"
          type="number"
          :min="0.01"
          maxlength="10"
          :placeholder="$t('menuList.pleaseEnterTheAmount')"
          @blur="handleInputValue(deliveryAmount,0.01,9999)"
        />
      </div>
    </el-form-item>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @close="addOrUpdateClose"
      @refresh-data-list="refreshChange"
    />
    <el-form-item>
      <el-table
        v-if="transportInfo.transfees && tableRate>0"
        :data="transportInfo.transfees"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('product.deliveryArea')"
          width="350"
        >
          <template #default="scope">
            <span v-if="!scope.row.cityList.length">{{ $t("transport.allRegions") }}</span>
            <el-tag
              v-for="(city,index) in scope.row.addrNameList"
              :key="index"
            >
              {{ city }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="firstPiece"
          :label="tableTitle[0]"
        />
        <el-table-column
          prop="firstFee"
          :label="tableTitle[1]"
        />
        <el-table-column
          prop="continuousPiece"
          :label="tableTitle[2]"
        />
        <el-table-column
          prop="continuousFee"
          :label="tableTitle[3]"
        />
      </el-table>
    </el-form-item>
    <el-form-item v-if="transportInfo.hasFreeCondition === 1 && tableRate === 1">
      <el-table
        :data="transportInfo.transfeeFrees"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('transport.selArea')"
          width="350"
        >
          <template #default="scope">
            <el-tag
              v-for="(city,index) in scope.row.freeAddrNameList"
              :key="index"
            >
              {{ city }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="freeType"
          :label="$t('transport.freeShippCondi')"
        >
          <template #default="scope">
            <span
              v-if="scope.row.freeType === 0"
            >{{ [$t("transport.fullCount"),$t("transport.fullWeight"),$t("transport.fullVolume")][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 1"
            >{{ $t('transport.fullAmount') + $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 2"
            >{{ [$t("transport.fullCount"),$t("transport.fullWeight"),$t("transport.fullVolume")][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount">
          <template #default="scope">
            <span
              v-if="scope.row.freeType === 1"
            >{{ $t("marketing.full") }}{{ scope.row.amount }}{{ $t("transport.yuan") }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 0"
            >{{ $t("marketing.full") }}{{ scope.row.piece }}{{ [$t("transport.pieces"),'kg','m³'][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 2"
            >{{ $t("marketing.full") }}{{ scope.row.piece }}{{ $t("transport.yuan") }}{{ $t("transport.andFull") }} {{ scope.row.amount }} {{ [$t("transport.pieces"),'kg','m³'][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </div>
</template>

<script setup>
import { areaNameList } from '@/utils/addr.js'
import AddOrUpdate from '@/components/freight-template/index.vue'

const emit = defineEmits(['changeInfo'])
const props = defineProps({
  transportData: {
    default: () => {},
    type: Object
  }
})
const transportList = ref([{
  transportId: null,
  transName: ''
}])
const transportInfo = ref({
  hasFreeCondition: false,
  transfeeFrees: [{ freeCityList: [] }]
})

const tableTitle = computed(() => {
  const titles = [
    [
      $t('transport.firstPiece'),
      $t('transport.transportationCost'),
      $t('transport.continuationPiece'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstWeight'),
      $t('transport.transportationCost'),
      $t('transport.continuedWeight'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstVolume'),
      $t('transport.transportationCost'),
      $t('transport.continuedVolume'),
      $t('transport.continuationCost')
    ]
  ]
  if (transportInfo.value.chargeType) {
    return titles[transportInfo.value.chargeType]
  }
  return titles[0]
})
const tableRate = ref(-1) // 0 包邮 -1 固定运费 大于0运费模板id
const transportId = ref(0)
const deliveryAmount = ref(0.01)
watch(() => props.transportData, (val) => {
  transportId.value = val.deliveryTemplateId
  tableRate.value = val.deliveryTemplateId > 0 ? 1 : val.deliveryTemplateId
  deliveryAmount.value = val.deliveryAmount
})
// transportId发生改变，就改变表格
watch([transportId, deliveryAmount], () => {
  changeTransport()
})
watch(tableRate, () => {
  changeTransport(tableRate.value === -1)
})
const addOrUpdateVisible = ref(false)
const addOrUpdateClose = () => {
  addOrUpdateVisible.value = false
}
onMounted(() => {
  getTransportList()
})
// 新增
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
const refreshChange = (transName) => {
  getTransportList(transName)
}
const getTransportList = (transName) => {
  http({
    url: http.adornUrl('/shop/transport/list'),
    method: 'get',
    params: http.adornParams({})
  }).then(({ data }) => {
    transportList.value = data
    transportList.value.forEach(item => {
      if (item.transName === String(transName)) {
        transportId.value = item.transportId
      }
    })
  })
}
const changeTransport = (status = false) => {
  if (tableRate.value === 1 && transportId.value <= 0) {
    transportId.value = ''
  }
  deliveryAmount.value = status ? 0.01 : deliveryAmount.value
  emit('changeInfo', {
    transportId: transportId.value,
    tableRate: tableRate.value,
    deliveryAmount: deliveryAmount.value
  })
  if (transportId.value && tableRate.value === 1) {
    http({
      url: http.adornUrl(`/shop/transport/info/${transportId.value}`),
      method: 'get',
      params: http.adornParams({})
    }).then(({ data }) => {
      transportInfo.value = data
      getAreaListInfo()
    })
  }
}
const getAreaListInfo = () => {
  http({
    url: http.adornUrl('/admin/area/areaListInfo'),
    method: 'get'
  }).then(({ data }) => {
    for (let t = 0; t < transportInfo.value.transfees.length; t++) {
      const areaList = JSON.parse(JSON.stringify(data))
      transportInfo.value.transfees[t].addrNameList = areaNameList(areaList, transportInfo.value.transfees[t].cityList)
    }
    for (let f = 0; f < transportInfo.value.transfeeFrees.length; f++) {
      const areaList = JSON.parse(JSON.stringify(data))
      transportInfo.value.transfeeFrees[f].freeAddrNameList = areaNameList(areaList, transportInfo.value.transfeeFrees[f].freeCityList)
    }
  })
}

/**
 * 处理输入框数据
 * @param data
 * @param dataFields
 * @param min 最小值
 * @param max 最大值
 */
const handleInputValue = (data, min, max) => {
  deliveryAmount.value = checkInput(data)
  if (data || data === 0) {
    // 保留两位小数
    if (data > max) {
      deliveryAmount.value = max
    }
    if (data < min) {
      deliveryAmount.value = min
    }
  }
}
/**
 * 只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = String(num).replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

const freight = () => {
  deliveryAmount.value = !deliveryAmount.value ? 0.01 : deliveryAmount.value
}

</script>

<style lang="scss" scoped>
.components-prod-transport {
  :deep(.el-tag) {
    margin-right: 10px;
  }
}
</style>
